#include "ordermanage.h"
#include "ui_ordermanage.h"
#include "adminmainwindow.h"
#include <QHeaderView>
#include <QPushButton>
#include <QMessageBox>
#include <QDateTime>
#include <QDebug>
#include <QDate>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QFileDialog>
#include <QTextStream>
#include <QApplication>
#include <QProgressDialog>
#include <QRegExp>
#include <QLocale>

// Qt 5.3 兼容性定义
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
#define QRandomGenerator qrand
#endif

OrderManage::OrderManage(QSqlDatabase db, QWidget *parent) :
    QDialog(parent), m_db(db),  // 保存数据库连接到成员变量
    ui(new Ui::OrderManage),
    model(new QStandardItemModel(this)),
    currentSearchText(""),
    currentStatusFilter(""),
    currentDateFilter("")
{
    ui->setupUi(this);

    // 检查数据库连接是否有效
    if (!m_db.isOpen()) {
        QMessageBox::critical(this, "数据库错误", "数据库连接未打开");
        return;
    }

    // 设置窗口标题和大小
    setWindowTitle("花店订单管理系统");
    resize(800, 600);

    // 初始化界面组件
    initFilters();

    setupConnections();
    loadDataFromDatabase();
}

OrderManage::~OrderManage()
{
    delete ui;
}

void OrderManage::initFilters()
{
    // 初始化状态筛选下拉框
    ui->statusCombo->clear();
    ui->statusCombo->addItem("全部状态", "");
    ui->statusCombo->addItem("待支付", "待支付");
    ui->statusCombo->addItem("已支付", "已支付");
    ui->statusCombo->addItem("已完成", "已完成");

    // 初始化日期筛选下拉框
    ui->dateCombo->clear();
    ui->dateCombo->addItem("全部日期", "");
    ui->dateCombo->addItem("今天", "today");
    ui->dateCombo->addItem("本周", "week");
    ui->dateCombo->addItem("本月", "month");

    // 设置表格视图
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->verticalHeader()->setVisible(false);

    // 设置数据模型
    model->setHorizontalHeaderLabels({
        "订单ID", "客户姓名", "电话", "下单时间", "状态", "金额(¥)", "操作"
    });
    ui->tableView->setModel(model);

    // 设置列宽 - Qt 5.3 使用 setResizeMode
    ui->tableView->setColumnWidth(0, 80);   // ID
    ui->tableView->setColumnWidth(1, 100);  // 姓名
    ui->tableView->setColumnWidth(2, 120);  // 电话
    ui->tableView->setColumnWidth(3, 150);  // 时间
    ui->tableView->setColumnWidth(4, 100);  // 状态
    ui->tableView->setColumnWidth(5, 100);  // 金额
    ui->tableView->horizontalHeader()->setSectionResizeMode(6, QHeaderView::Stretch);
}

void OrderManage::setupConnections()
{
    // 连接信号槽 - 使用 Qt 5.3 兼容的旧语法
    connect(ui->searchEdit, SIGNAL(textChanged(QString)),
            this, SLOT(onSearchTextChanged(QString)));

    connect(ui->statusCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(onStatusFilterChanged(int)));

    connect(ui->dateCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(onDateFilterChanged(int)));
}

void OrderManage::addSampleData()
{
    // 添加示例订单
    QList<QStandardItem*> row1;
    row1 << new QStandardItem("#1001");
    row1 << new QStandardItem("张伟");
    row1 << new QStandardItem("13800138000");
    row1 << new QStandardItem(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm"));
    row1 << new QStandardItem("已付款");
    row1 << new QStandardItem("199.00");
    row1[4]->setForeground(Qt::darkGreen); // 状态颜色

    QPushButton *detailBtn1 = new QPushButton("详情", this);
    connect(detailBtn1, SIGNAL(clicked()), this, SLOT(showOrderDetails()));

    model->appendRow(row1);
    ui->tableView->setIndexWidget(model->index(0, 6), detailBtn1);

    // 添加第二个示例订单
    QList<QStandardItem*> row2;
    row2 << new QStandardItem("#1002");
    row2 << new QStandardItem("李芳");
    row2 << new QStandardItem("13900139000");
    row2 << new QStandardItem(QDateTime::currentDateTime().addDays(-1).toString("yyyy-MM-dd hh:mm"));
    row2 << new QStandardItem("配送中");
    row2 << new QStandardItem("299.00");
    row2[4]->setForeground(QColor(255, 165, 0)); // 橙色

    QPushButton *detailBtn2 = new QPushButton("详情", this);
    connect(detailBtn2, SIGNAL(clicked()), this, SLOT(showOrderDetails()));

    model->appendRow(row2);
    ui->tableView->setIndexWidget(model->index(1, 6), detailBtn2);

    // 添加第三个示例订单（不同状态）
    QList<QStandardItem*> row3;
    row3 << new QStandardItem("#1003");
    row3 << new QStandardItem("王明");
    row3 << new QStandardItem("13700137000");
    row3 << new QStandardItem(QDateTime::currentDateTime().addDays(-3).toString("yyyy-MM-dd hh:mm"));
    row3 << new QStandardItem("待付款");
    row3 << new QStandardItem("159.00");
    row3[4]->setForeground(Qt::red); // 红色

    QPushButton *detailBtn3 = new QPushButton("详情", this);
    connect(detailBtn3, SIGNAL(clicked()), this, SLOT(showOrderDetails()));

    model->appendRow(row3);
    ui->tableView->setIndexWidget(model->index(2, 6), detailBtn3);
}

// 应用所有筛选条件
void OrderManage::applyFilters()
{
    QDate today = QDate::currentDate();
    QDate weekStart = today.addDays(1 - today.dayOfWeek()); // 本周第一天

    // 列索引常量定义
    const int ORDER_ID_COLUMN = 0;      // 订单ID列
    const int NAME_COLUMN = 1;          // 姓名列
    const int PHONE_COLUMN = 2;         // 电话列
    const int DATE_COLUMN = 3;          // 日期列
    const int STATUS_COLUMN = 4;        // 状态列
    const int RATING_COLUMN = 7;        // 评分列（假设在第7列，根据实际调整）

    for (int row = 0; row < model->rowCount(); ++row) {
        bool matchSearch = currentSearchText.isEmpty();
        bool matchStatus = currentStatusFilter.isEmpty();
        bool matchDate = currentDateFilter.isEmpty();

        // 搜索匹配
        if (!matchSearch) {
            for (int col : {ORDER_ID_COLUMN, NAME_COLUMN, PHONE_COLUMN, RATING_COLUMN}) {
                if (QStandardItem* item = model->item(row, col)) {
                    QString itemText = item->text();

                    // 特殊处理订单ID列
                    if (col == ORDER_ID_COLUMN) {
                        bool matched = false;

                        // 方式1: 作为数字完全匹配
                        bool isNumber;
                        int orderId = itemText.toInt(&isNumber);
                        if (isNumber) {
                            bool searchIsNumber;
                            int searchNumber = currentSearchText.toInt(&searchIsNumber);
                            if (searchIsNumber && orderId == searchNumber) {
                                matched = true;
                            }
                        }

                        // 方式2: 作为字符串包含匹配
                        if (!matched && itemText.contains(currentSearchText, Qt::CaseInsensitive)) {
                            matched = true;
                        }

                        // 方式3: 处理可能的订单号格式
                        if (!matched) {
                            QString cleanOrderId = itemText;
                            cleanOrderId.remove(QRegExp("[^0-9]"));

                            QString cleanSearch = currentSearchText;
                            cleanSearch.remove(QRegExp("[^0-9]"));

                            if (!cleanOrderId.isEmpty() && !cleanSearch.isEmpty() &&
                                cleanOrderId.contains(cleanSearch)) {
                                matched = true;
                            }
                        }

                        if (matched) {
                            matchSearch = true;
                            break;
                        }
                    }
                    // 其他列使用常规字符串匹配
                    else if (itemText.contains(currentSearchText, Qt::CaseInsensitive)) {
                        matchSearch = true;
                        break;
                    }
                }
            }
        }

        // 状态匹配
        if (!matchStatus && currentStatusFilter != "全部状态") {
            if (QStandardItem* statusItem = model->item(row, STATUS_COLUMN)) {
                QString itemStatus = statusItem->text().trimmed();
                if (itemStatus == currentStatusFilter) {
                    matchStatus = true;
                }
            }
        }

        // 日期匹配
        if (!matchDate) {
            QStandardItem* dateItem = model->item(row, DATE_COLUMN);
            if (dateItem && !dateItem->text().isEmpty()) {
                QString dateText = dateItem->text();
                QDateTime orderDate;

                // 尝试多种日期格式解析
                QStringList formats = {
                    "yyyy-MM-dd hh:mm:ss",
                    "yyyy-MM-dd",
                    "yyyy/MM/dd",
                    "dd/MM/yyyy"
                };

                foreach (const QString &format, formats) {
                    orderDate = QDateTime::fromString(dateText, format);
                    if (orderDate.isValid()) break;
                }

                if (!orderDate.isValid()) {
                    orderDate = QDateTime::fromString(dateText, Qt::ISODate);
                }

                if (!orderDate.isValid()) {
                    orderDate = QLocale().toDateTime(dateText, QLocale::ShortFormat);
                }

                if (orderDate.isValid()) {
                    QDate date = orderDate.date();

                    if (currentDateFilter == "today") {
                        matchDate = (date == today);
                    }
                    else if (currentDateFilter == "week") {
                        matchDate = (date >= weekStart && date <= today);
                    }
                    else if (currentDateFilter == "month") {
                        matchDate = (date.month() == today.month() && date.year() == today.year());
                    }
                }
            }
        }

        // 显示/隐藏行
        bool showRow = matchSearch && matchStatus && matchDate;
        ui->tableView->setRowHidden(row, !showRow);
    }
}

void OrderManage::onSearchTextChanged(const QString &text)
{
    currentSearchText = text;
    applyFilters();
}

void OrderManage::onStatusFilterChanged(int index)
{
    currentStatusFilter = ui->statusCombo->itemData(index).toString();
    applyFilters();
}

void OrderManage::onDateFilterChanged(int index)
{
    currentDateFilter = ui->dateCombo->itemData(index).toString();
    applyFilters();
}

void OrderManage::showOrderDetails()
{
    // 获取发送信号的按钮
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;

    // 找到按钮所在的行
    int row = -1;
    for (int i = 0; i < model->rowCount(); ++i) {
        if (ui->tableView->indexWidget(model->index(i, 6))) {
            QPushButton *btn = qobject_cast<QPushButton*>(ui->tableView->indexWidget(model->index(i, 6)));
            if (btn == button) {
                row = i;
                break;
            }
        }
    }

    if (row >= 0) {
        QString orderId = model->item(row, 0)->text();
        QString customer = model->item(row, 1)->text();
        QString status = model->item(row, 4)->text();
        QString amount = model->item(row, 5)->text();

        QString details = QString("订单详情\n\n"
                                 "订单ID: %1\n"
                                 "客户姓名: %2\n"
                                 "状态: %3\n"
                                 "金额: ¥%4\n\n"
                                 "")
                          .arg(orderId)
                          .arg(customer)
                          .arg(status)
                          .arg(amount);

        QMessageBox::information(this, "订单详情 - " + orderId, details);
    }
}

void OrderManage::loadDataFromDatabase()
{
    // 清空现有数据
    model->removeRows(0, model->rowCount());

    // 使用参数化查询（虽然此处没有参数，但格式更规范）
    QSqlQuery query(m_db); // 使用成员变量m_db而不是局部变量

    QString sql = "SELECT "
                  "    Orders.order_id, "
                  "    login_users.username, "
                  "    login_users.phone, "
                  "    Orders.total_price, "
                  "    Orders.create_time, "
                  "    Orders.status "
                  "FROM "
                  "    Orders "
                  "JOIN "
                  "    login_users ON Orders.user_id = login_users.user_id "
                  "ORDER BY "
                  "    Orders.create_time DESC"; // 按创建时间降序排列

    qDebug() << "执行SQL查询:" << sql;

    if (!query.exec(sql)) {
        QMessageBox::critical(this, "查询错误",
                            "数据查询失败: " + query.lastError().text());
        qDebug() << "SQL错误:" << query.lastError().text();
        return;
    }

    // 记录查询结果数量
    int rowCount = 0;

    // 遍历查询结果，添加到表格模型
    while (query.next()) {
        QList<QStandardItem*> row;

        // 订单ID
        QString orderId = query.value("order_id").toString();
        row << new QStandardItem(orderId);

        // 客户姓名
        row << new QStandardItem(query.value("username").toString());

        // 电话
        row << new QStandardItem(query.value("phone").toString());

        // 下单时间（格式化显示）
        QString timeStr = query.value("create_time").toString();
        QDateTime orderTime = QDateTime::fromString(timeStr, "yyyy-MM-dd hh:mm:ss");

        // 如果解析失败，尝试仅日期格式
        if (!orderTime.isValid()) {
            orderTime = QDateTime::fromString(timeStr, "yyyy-MM-dd");
        }

        // 如果仍然失败，使用原始字符串
        if (orderTime.isValid()) {
            row << new QStandardItem(orderTime.toString("yyyy-MM-dd hh:mm"));
        } else {
            row << new QStandardItem(timeStr);
        }

        // 订单状态（设置颜色）
        QString status = query.value("status").toString().trimmed();
        QStandardItem* statusItem = new QStandardItem(status);

        if (status == "待付款") {
            statusItem->setForeground(Qt::red);
        } else if (status == "已付款") {
            statusItem->setForeground(Qt::darkGreen);
        } else if (status == "配送中") {
            statusItem->setForeground(QColor(255, 165, 0));
        } else if (status == "已完成") {
            statusItem->setForeground(Qt::blue);
        }
        row << statusItem;

        // 金额（格式化显示）
        double amount = query.value("total_price").toDouble();
        row << new QStandardItem(QString::number(amount, 'f', 2));

        // 添加"详情"按钮
        QPushButton* detailBtn = new QPushButton("详情", this);
        connect(detailBtn, &QPushButton::clicked, this, &OrderManage::showOrderDetails);

        // 添加行到模型
        model->appendRow(row);
        // 设置按钮到表格
        int rowIndex = model->rowCount() - 1;
        ui->tableView->setIndexWidget(model->index(rowIndex, 6), detailBtn);

        rowCount++;
    }

    qDebug() << "成功加载" << rowCount << "条订单数据";

    // 如果没有数据，显示提示
    if (rowCount == 0) {
        QMessageBox::information(this, "数据为空", "当前没有订单数据");
    }

    // 强制刷新表格
    model->layoutChanged();
}


void OrderManage::on_pushButton_clicked()
{
    QWidget *parentWidget = qobject_cast<QWidget*>(parent());
    if (parentWidget) {
        parentWidget->show();
    } else {
        adminMainWindow *m = new adminMainWindow(m_db);
        m->setAttribute(Qt::WA_DeleteOnClose);
        m->show();
    }
    this->close();
}

void OrderManage::on_exportButton_clicked()
{
    // 弹出文件选择对话框
    QString filePath = QFileDialog::getSaveFileName(
        this,
        "导出CSV文件",
        QDir::homePath() + "/订单数据_" + QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + ".csv",
        "CSV文件 (*.csv);;所有文件 (*)"
    );

    if (filePath.isEmpty()) {
        return;
    }

    // 确保文件以.csv结尾
    if (!filePath.endsWith(".csv", Qt::CaseInsensitive)) {
        filePath += ".csv";
    }

    // 获取所有可见行的数据
    QList<QList<QString>> exportData;

    // 添加表头
    QList<QString> headerRow;
    for (int col = 0; col < model->columnCount() - 1; ++col) {  // 排除最后一列（操作列）
        headerRow << model->horizontalHeaderItem(col)->text();
    }
    exportData << headerRow;

    // 收集表格数据（只导出可见行）
    int visibleRowCount = 0;
    for (int row = 0; row < model->rowCount(); ++row) {
        if (!ui->tableView->isRowHidden(row)) {  // 只处理可见行
            QList<QString> dataRow;
            for (int col = 0; col < model->columnCount() - 1; ++col) {  // 排除操作列
                QStandardItem* item = model->item(row, col);
                dataRow << (item ? item->text() : "");
            }
            exportData << dataRow;
            visibleRowCount++;
        }
    }

    // 显示导出进度
    QProgressDialog progress("正在导出数据...", "取消", 0, exportData.size(), this);
    progress.setWindowTitle("导出中");
    progress.setWindowModality(Qt::WindowModal);
    progress.show();

    // 写入CSV文件
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "文件错误",
            QString("无法打开文件进行写入：%1\n%2")
            .arg(filePath)
            .arg(file.errorString()));
        return;
    }

    QTextStream out(&file);
    // 设置UTF-8 BOM，解决中文乱码问题
    out.setCodec("UTF-8");
    out << "\xEF\xBB\xBF";  // UTF-8 BOM

    for (int i = 0; i < exportData.size(); ++i) {
        // 检查是否取消导出
        if (progress.wasCanceled()) {
            file.close();
            QFile::remove(filePath);  // 删除不完整文件
            QMessageBox::information(this, "导出取消", "数据导出已取消");
            return;
        }

        const QList<QString>& row = exportData[i];
        QStringList csvRow;

        // 处理每个单元格，确保CSV格式正确
        for (const QString& cell : row) {
            if (cell.contains(',') || cell.contains('"') || cell.contains('\n') || cell.contains('\r')) {
                QString escaped = cell;
                escaped.replace("\"", "\"\"");
                csvRow << QString("\"%1\"").arg(escaped);
            } else {
                csvRow << cell;
            }
        }

        // 写入一行数据，用逗号分隔
        out << csvRow.join(',') << "\n";

        // 更新进度
        progress.setValue(i + 1);
        QApplication::processEvents();  // 刷新界面
    }

    file.close();
    progress.close();

    // 导出完成提示
    QMessageBox::information(
        this,
        "导出成功",
        QString("数据已成功导出到：\n%1\n共导出 %2 条记录")
        .arg(filePath)
        .arg(visibleRowCount)
    );
}
